<?php

namespace backend\models;

use Yii;
use yii\web\UploadedFile;

/**
 * This is the model class for table "furniture".
 *
 * @property int $id
 * @property int $id_type
 * @property string|null $brand
 * @property string|null $scheme_img
 * @property string|null $color
 * @property int|null $dimensions_height
 * @property int|null $dimensions_width
 * @property int|null $dimensions_depth
 * @property int|null $amount
 *
 * @property FurnitureType $type
 */
class Furniture extends \yii\db\ActiveRecord
{
    public $imageFile;

    const BUCKET_NAME = 'ogikm-img-internal';

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'furniture';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id_type'], 'required'],
            [['id_type', 'dimensions_height', 'dimensions_width', 'dimensions_depth', 'amount'], 'integer'],
            [['brand', 'scheme_img', 'color'], 'string', 'max' => 255],
            [['id_type'], 'exist', 'skipOnError' => true, 'targetClass' => FurnitureType::className(), 'targetAttribute' => ['id_type' => 'id']],
            [['imageFile'], 'file', 'extensions' => 'jpg, png'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'id_type' => 'Тип',
            'brand' => 'Название',
            'scheme_img' => 'Имя файла изображения',
            'imageFile' => 'Изображение',
            'color' => 'Цвет',
            'dimensions_height' => 'Высота',
            'dimensions_width' => 'Ширина',
            'dimensions_depth' => 'Глубина',
            'amount' => 'Количество',
        ];
    }

    /**
     * Gets query for [[Type]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getType()
    {
        return $this->hasOne(FurnitureType::className(), ['id' => 'id_type']);
    }

    public function beforeDelete()
    {
        if (!parent::beforeDelete()) {
            return false;
        }

        $this->deleteImageFile($this->scheme_img);
        
        return true;
    }

    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
            return false;
        }

        if($insert)
        {
            if($this->imageFile)
            {
                $this->processCoverImage();   
            }
        }
        else
        {
            if($this->imageFile)
            {
                $this->deleteImageFile($this->scheme_img);
                $this->processCoverImage();
            }
        }
        
        return true;
    }

    public function processCoverImage()
    {
        if(!$this->scheme_img)
        {
            $generatedName = $this->generateFileName($this->imageFile);
            $this->scheme_img = $generatedName;
        }           

        $this->uploadImage($this->imageFile, $this->scheme_img);
    }

    private function deleteImageFile($fileName)
    {
        if($fileName)
        {
            $s3 = Yii::$app->get('s3');
            $s3->commands()->delete($fileName)->inBucket(self::BUCKET_NAME)->execute();
        }
    }

    private function uploadImage($file, $fileName)
    {
        if($file)
        {
            $s3 = Yii::$app->get('s3');
            $result = $s3->commands()->upload($fileName, $file->tempName)->inBucket(self::BUCKET_NAME)->withAcl('private')->execute();
        }
    }

    private function generateFileName($file)
    {
        return uniqid() . '.' . $file->extension;
    }
}
